package org.leo.tree.handler;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.leo.tree.beans.Output;

public class LocationFetcher {
	public Output getLocationOutput(String address) {
		Output output = new Output();

		URL url;
		InputStream is = null;
		DataInputStream dis;
		String line;

		try {
			String strUrl = new StringBuffer(
					"http://maps.googleapis.com/maps/api/geocode/json?address=")
					.append(address).append("&sensor=false")
					.toString();
			System.out.println("Url : " + strUrl);
			url = new URL(strUrl);
			is = url.openStream(); // throws an IOException
			dis = new DataInputStream(new BufferedInputStream(is));

			while ((line = dis.readLine()) != null) {
				JSONObject json = (JSONObject) JSONSerializer.toJSON(line);
				System.out.println("Recvd json : " + json);
				if (json.getString("status").equalsIgnoreCase("OK")) {
					JSONArray results = json.getJSONArray("results");
					JSONObject fRes = (JSONObject) results.get(0);
					JSONObject geometry = fRes.getJSONObject("geometry");
					JSONObject location = geometry.getJSONObject("location");
					String lat = location.getString("lat");
					String lng = location.getString("lng");
					output.setAddress(address);
					output.setLat(lat);
					output.setLng(lng);
				}
			}
		} catch (MalformedURLException mue) {
			mue.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException ioe) {
				// nothing to see here
			}
		}

		return output;
	}
}
